package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate ;

    @Autowired
    private OrdersService ordersService;
    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);

            // 调用阿里云提供的短信服务API完成发送短信
            // SMSUtils.sendMessage("", "", phone, code);

            // 将验证码保存到session中
            // session.setAttribute(phone, code);

            // 将验证码保存到redis中，并设置过期时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        //从session中获取保存的验证码
//        Object codeSession = session.getAttribute(phone);

        //从Redis中获取保存的验证码
        Object codeSession = redisTemplate.opsForValue().get(phone);

        //进行验证码比对（页面提交的验证码和session保存的验证码进行比对）
        if (codeSession!=null && codeSession.equals(code)){
            //如果为TRUE，说明登录成功
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);

            if (user==null){
                //判断当前用户是否为新用户，是责自动注册
                user = new User();
                user.setName("匿名用户");
                user.setPhone(phone);
                user.setStatus(1);
                user.setAvatar("headPage.png");
                userService.save(user);
            }
            session.setAttribute("user",user.getId());



            return R.success(user);
        }
        return R.error("登录失败!");
    }


    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 回显个人信息
     *
     * @return
     */
    @GetMapping("/list")
    public R<User> list() {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
//        Long currentId = BaseContext.getCurrentId();
        lqw.eq(User::getId, BaseContext.getCurrentId());
        User user = userService.getOne(lqw);
        return R.success(user);
    }


    /**
     * 修改个人信息
     * @param user
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody User user) {
        log.info("user:{}", user);
        System.out.println(user);
        userService.updateById(user);
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Orders::getUserName, user.getName());
        updateWrapper.eq(Orders::getUserId, user.getId());
        ordersService.update(updateWrapper);
        return R.success("信息修改成功！");
    }
}
